package main

import (
	"os"
	"fmt"
	"io/ioutil"
	"compress/gzip"
	"io"
)

/*
   @Time : 2018/8/29 14:34 
   @Author : ff
*/
func main() {
	//write()
	//ioutilWrite()
	//ioutilRead()

	//gzipTest()

	copyFileTest()
}



func write()  {
	file, err := os.OpenFile("./test.dat", os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("open file failed, err:", err)
		return
	}

	defer file.Close()
	str := "hello world"
	file.Write([]byte(str))
	file.WriteString(str)
}

func ioutilWrite()  {
	str := "hello world"
	err := ioutil.WriteFile("./test.dat", []byte(str), 0755)
	if err != nil {
		fmt.Println("write file failed, err:", err)
		return
	}
}

func ioutilRead()  {
	bt, err := ioutil.ReadFile("./README.md")
	if err != nil{
		fmt.Println("read file failed :",err)
		return
	}

	fmt.Println("ioutil read file ,content: ",string(bt))
}

/**
  读取压缩文件
 */
func gzipTest()  {
	file,err := os.Open("./main.go.gz")
	if err != nil {
		fmt.Println("open gzip failed : ",err)
		return
	}
	//最后关闭
	defer file.Close()

	reader , err := gzip.NewReader(file)
	if err != nil {
		fmt.Println("read gzip failed : ",err)
		return
	}

	var content []byte
	var buf [128]byte

	for {
		n , err := reader.Read(buf[:])
		if err == io.EOF {
			if n != 0 {
				content = append(content,buf[:n]...)
				break
			}

		}

		if err != nil {
			fmt.Println("read file err : ",err)
			return
		}

		content = append(content,buf[:n]...)
	}

	fmt.Println("read gzip file content : ",string(content))
}

/**
   dstName：目标文件
   srcName：源文件
 */
func CopyFile(dstName , srcName string) (write int64,err error){
	src,err := os.Open(srcName)
	if err != nil {
		fmt.Println("open src failed")
		return
	}
	defer src.Close()

	dst,err := os.OpenFile(dstName,os.O_WRONLY | os.O_CREATE,0644)
	if err != nil {
		fmt.Println("open dst failed")
		return
	}
	defer dst.Close()
	return io.Copy(dst,src)
}

func copyFileTest()  {
	_,err := CopyFile("test.dat","README.md")
	if err == nil {
		fmt.Println("copy finished ！")
	}
}